document.addEventListener('DOMContentLoaded', function() {
  // 首先检查密码验证状态
  checkPasswordAuth().then(isAuthorized => {
    if (!isAuthorized) {
      showPasswordDialog();
      return;
    }
    
    // 密码验证通过后，初始化正常功能
    initializeExtension();
  });
  
  function initializeExtension() {
    const startBtn = document.getElementById('startBtn');
    const stopBtn = document.getElementById('stopBtn');
    const exportBtn = document.getElementById('exportBtn');
    const loginStatus = document.getElementById('loginStatus');
    const progress = document.getElementById('progress');
    const currentPageEl = document.getElementById('currentPage');
    const totalPagesEl = document.getElementById('totalPages');
    const videoCountEl = document.getElementById('videoCount');
    const scrollDelayInput = document.getElementById('scrollDelay');
    

    

    
    // 检查登录状态
    checkLoginStatus();
    
    // 加载已保存的设置
    loadSettings();
    
    // 加载爬取进度
    loadProgress();
    
    // 保存设置
    scrollDelayInput.addEventListener('change', saveSettings);
    
    
    
    // 开始爬取按钮
    startBtn.addEventListener('click', function() {
      const scrollDelay = parseInt(scrollDelayInput.value);
    
    // 只保存scrollDelay和isRunning
    chrome.storage.local.set({
      scrollDelay: scrollDelay,
      isRunning: true
    });
    
    // 隐藏/重置进度条
    progress.style.display = 'none';
    
    // 发送消息到content script，只传递scrollDelay
    chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
      chrome.tabs.sendMessage(tabs[0].id, {
        action: 'startScraping',
        scrollDelay: scrollDelay
      });
    });
    
    // 更新按钮状态
    startBtn.disabled = true;
    stopBtn.disabled = false;
    exportBtn.disabled = true;
  });
  
  // 停止爬取按钮
  stopBtn.addEventListener('click', function() {
    chrome.storage.local.set({isRunning: false});
    
    // 发送消息到content script停止爬取
    chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
      chrome.tabs.sendMessage(tabs[0].id, {action: 'stopScraping'});
    });
    
    // 更新按钮状态
    startBtn.disabled = false;
    stopBtn.disabled = true;
    
    // 检查是否有数据可以导出
    chrome.storage.local.get(['scrapedData'], function(result) {
      const hasData = result.scrapedData && result.scrapedData.length > 0;
      exportBtn.disabled = !hasData;
      
    });
  });
  

  
  // 导出数据按钮
  exportBtn.addEventListener('click', function() {
    exportBtn.textContent = '导出中...';
    exportBtn.disabled = true;
    
    chrome.storage.local.get(['scrapedData'], function(result) {
      if (result.scrapedData && result.scrapedData.length > 0) {
        exportToCSV(result.scrapedData);
        setTimeout(() => {
          exportBtn.textContent = '导出数据 (CSV)';
          exportBtn.disabled = false;
        }, 2000);
              } else {
          alert('没有可导出的数据');
          exportBtn.textContent = '导出数据 (CSV)';
          exportBtn.disabled = false;
        }
    });
  });
  
  // 检查登录状态
  function checkLoginStatus() {
    console.log('popup.js: 开始检查登录状态');
    chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
      const url = tabs[0].url;
      console.log('当前页面URL:', url);
      
      if (url && url.includes('buyin.jinritemai.com')) {
        console.log('在抖音大人后台页面，发送检查登录状态消息');
        chrome.tabs.sendMessage(tabs[0].id, {action: 'checkLoginStatus'}, function(response) {
          console.log('收到登录状态响应:', response);
          
          if (response && response.loggedIn) {
            console.log('用户已登录，启用爬取按钮');
            loginStatus.className = 'status logged-in';
            loginStatus.textContent = '已登录';
            startBtn.disabled = false;
            
            // 检查是否有数据可以导出和是否正在运行
            chrome.storage.local.get(['scrapedData', 'isRunning'], function(result) {
              const hasData = result.scrapedData && result.scrapedData.length > 0;
              const isRunning = result.isRunning;
              
                          exportBtn.disabled = !hasData;

              
              // 如果正在运行，更新按钮状态
              if (isRunning) {
                startBtn.disabled = true;
                stopBtn.disabled = false;
              }
            });
          } else {
            console.log('用户未登录，禁用爬取按钮');
            loginStatus.className = 'status logged-out';
            loginStatus.textContent = '未登录，请先登录抖音大人后台';
            startBtn.disabled = true;
            exportBtn.disabled = true;


          }
        });
      } else {
        console.log('不在抖音大人后台页面');
        loginStatus.className = 'status logged-out';
        loginStatus.textContent = '请打开抖音大人后台页面';
        startBtn.disabled = true;
                    exportBtn.disabled = true;
      }
    });
  }
  
  // 加载设置
  function loadSettings() {
    chrome.storage.local.get(['scrollDelay'], function(result) {
      if (result.scrollDelay) {
        scrollDelayInput.value = result.scrollDelay;
      }
    });
  }
  
  // 保存设置
  function saveSettings() {
    chrome.storage.local.set({
      scrollDelay: parseInt(scrollDelayInput.value)
    });
  }
  
  // 加载爬取进度
  function loadProgress() {
    chrome.storage.local.get(['currentPage', 'totalPages', 'videoCount', 'isRunning'], function(result) {
      if (result.currentPage && result.totalPages) {
        progress.style.display = 'block';
        currentPageEl.textContent = result.currentPage;
        totalPagesEl.textContent = result.totalPages;
        videoCountEl.textContent = result.videoCount || '0';
        
        // 更新按钮状态
        if (result.isRunning) {
          startBtn.disabled = true;
          stopBtn.disabled = false;
          
        } else {
          startBtn.disabled = false;
          stopBtn.disabled = true;
          
        }
      }
    });
  }
  
  // 导出CSV（支持首行冻结说明）
  function exportToCSV(data) {
    let csvContent = "data:text/csv;charset=utf-8,";
    
    // 添加BOM标记，解决中文乱码问题
    csvContent = "data:text/csv;charset=utf-8,\ufeff";
    
    // 添加Excel首行冻结说明（在CSV开头添加注释行）
    csvContent += "# ==========================================\r\n";
    csvContent += "# Excel首行冻结设置说明：\r\n";
    csvContent += "# 1. 在Excel中打开此文件\r\n";
    csvContent += "# 2. 选择第一行（表头）\r\n";
    csvContent += "# 3. 点击：视图 -> 冻结窗格 -> 冻结首行\r\n";
    csvContent += "# 4. 或者：视图 -> 冻结窗格 -> 冻结第一行\r\n";
    csvContent += "# ==========================================\r\n";
    csvContent += "\r\n";
    
    // 添加CSV头部 - 更新为完整的字段列表
    const headers = [
      "页码", "视频ID", "视频标题", "作者昵称", "作者头像", "作者等级", "作者粉丝数",
      "点赞数", "播放量", "时段播放量", "视频时长", "是否优质视频",
      "GMV范围_原始值", "GMV范围_最小值", "GMV范围_最大值",
      "销量范围_原始值", "销量范围_最小值", "销量范围_最大值",
      "发布时间", "视频链接", "视频封面", "抖音视频地址", "产品ID", "推广ID", "产品名称", "产品封面",
      "客单价", "万播转化", "GPM"
    ];
    csvContent += headers.join(",") + "\r\n";
    
    // 添加数据行 - 处理新的数据结构
    data.forEach(function(item) {
      try {
        // 提取基础数据
        const page = item.page || "";
        const videoId = item.video_basic && item.video_basic.id ? item.video_basic.id : "";
        const title = item.video_basic && item.video_basic.title ? item.video_basic.title.replace(/"/g, '""') : "";
        
        // 作者信息
        const authorNickName = item.author_info && item.author_info.nick_name ? item.author_info.nick_name.replace(/"/g, '""') : "";
        const authorCover = item.author_info && item.author_info.cover ? item.author_info.cover : "";
        const authorLevel = item.author_info && item.author_info.level ? item.author_info.level : "";
        const fansNum = item.author_info && item.author_info.fans_num ? item.author_info.fans_num : "";
        
        // 视频基础数据
        const likes = item.video_basic && item.video_basic.likes ? item.video_basic.likes : "";
        const pageViews = item.video_basic && item.video_basic.page_views ? item.video_basic.page_views : "";
        const timeRangeViews = item.video_basic && item.video_basic.time_range_views ? item.video_basic.time_range_views : "";
        const duration = item.video_basic && item.video_basic.duration ? item.video_basic.duration : "";
        const isGreatVideo = item.video_basic && item.video_basic.is_great_video !== undefined ? item.video_basic.is_great_video.toString() : "";
        
        // GMV和销量范围
        const gmvRange = item.video_basic && item.video_basic.gmv_range ? item.video_basic.gmv_range : "";
        const salesRange = item.video_basic && item.video_basic.sales_range ? item.video_basic.sales_range : "";
        
        // 发布时间
        let publishTime = "";
        if (item.video_basic && item.video_basic.publish_time) {
          const timestamp = item.video_basic.publish_time;
          if (typeof timestamp === 'number' || !isNaN(parseInt(timestamp))) {
            try {
              const date = new Date(parseInt(timestamp) * 1000);
              publishTime = date.toISOString().replace('T', ' ').substring(0, 19);
            } catch (e) {
              publishTime = timestamp.toString();
            }
          } else {
            publishTime = timestamp.toString();
          }
        }
        
        // 视频链接和封面
        const videoUrl = item.video_basic && item.video_basic.url ? item.video_basic.url : "";
        const coverUrl = item.video_basic && item.video_basic.cover ? item.video_basic.cover : "";
        
        // 产品信息 - 优先从_original中获取，备选方案是video_basic
        let productId = "", promotionId = "", productName = "", productCover = "";
        let productList = null;
        
        // 优先尝试从_original.video_basic.product_list获取
        if (item._original && item._original.video_basic && item._original.video_basic.product_list && item._original.video_basic.product_list.length > 0) {
          productList = item._original.video_basic.product_list;
        }
        // 备选方案：从video_basic.product_list获取
        else if (item.video_basic && item.video_basic.product_list && item.video_basic.product_list.length > 0) {
          productList = item.video_basic.product_list;
        }
        
        if (productList && productList.length > 0) {
          const product = productList[0];
          productId = product.product_id || "";
          promotionId = product.promotion_id || "";
          productName = product.name ? product.name.replace(/"/g, '""') : "";
          productCover = product.cover || "";
        }
        
        // 计算抖音视频地址
        const douyinVideoUrl = videoId ? `https://www.douyin.com/video/${videoId}` : "";
        
        // 计算商业指标
        let unitPrice = "", wanBoConversion = "", gpm = "";
        try {
          // 解析GMV和销量范围
          const gmvMax = parseFloat(gmvRange.replace(/[^\d.]/g, '')) || 0;
          const salesMax = parseFloat(salesRange.replace(/[^\d.]/g, '')) || 0;
          const pageViewsNum = parseFloat(pageViews) || 0;
          
          // 客单价 = GMV范围_最大值 / 销量范围_最大值
          if (salesMax > 0) {
            unitPrice = (gmvMax / salesMax).toFixed(2);
          }
          
          // 万播转化 = 销量范围_最大值 / 播放量 * 10000
          if (pageViewsNum > 0) {
            wanBoConversion = ((salesMax / pageViewsNum) * 10000).toFixed(4);
          }
          
          // GPM = GMV范围_最大值 / 播放量 * 1000
          if (pageViewsNum > 0) {
            gpm = ((gmvMax / pageViewsNum) * 1000).toFixed(2);
          }
        } catch (e) {
          console.error("计算商业指标出错:", e);
        }
        
        const row = [
          page,
          videoId,
          title,
          authorNickName,
          authorCover,
          authorLevel,
          fansNum,
          likes,
          pageViews,
          timeRangeViews,
          duration,
          isGreatVideo,
          gmvRange,
          "", // GMV最小值
          "", // GMV最大值
          salesRange,
          "", // 销量最小值
          "", // 销量最大值
          publishTime,
          videoUrl,
          coverUrl,
          douyinVideoUrl,
          productId,
          promotionId,
          productName,
          productCover,
          unitPrice,
          wanBoConversion,
          gpm
        ];
        
        csvContent += row.map(field => `"${field}"`).join(",") + "\r\n";
      } catch (error) {
        console.error("处理数据行出错:", error);
        // 如果处理失败，添加空行
        const emptyRow = Array(headers.length).fill("").map(field => `"${field}"`).join(",");
        csvContent += emptyRow + "\r\n";
      }
    });
    
    // 创建下载链接
    const encodedUri = encodeURI(csvContent);
    const link = document.createElement("a");
    link.setAttribute("href", encodedUri);
    link.setAttribute("download", "抖音视频数据_" + new Date().toISOString().slice(0, 10) + ".csv");
    document.body.appendChild(link);
    
    // 触发下载
    link.click();
    document.body.removeChild(link);
    
    console.log(`成功导出 ${data.length} 条数据到CSV文件`);
  }
  
  } // 结束 initializeExtension 函数
  
  // ==================== 密码验证功能 ====================
  
  // 检查密码验证状态
  async function checkPasswordAuth() {
    return new Promise((resolve) => {
      chrome.storage.local.get(['passwordVerified'], function(result) {
        resolve(result.passwordVerified === true);
      });
    });
  }
  
  // 显示密码验证对话框
  function showPasswordDialog() {
    // 隐藏主界面内容
    const container = document.querySelector('.container');
    container.style.display = 'none';
    
    // 创建密码验证界面
    const passwordContainer = document.createElement('div');
    passwordContainer.id = 'passwordContainer';
    passwordContainer.innerHTML = `
      <div class="password-dialog">
        <div class="password-header">
          <h2>🔐 插件激活验证</h2>
          <p>请输入授权密码以使用此插件</p>
        </div>
        <div class="password-form">
          <input type="password" id="passwordInput" placeholder="请输入密码" />
          <button id="verifyBtn" class="btn btn-primary">验证密码</button>
        </div>
        <div class="password-footer">
          <p>联系获取密码：<strong>nmbff188</strong></p>
        </div>
      </div>
    `;
    
    document.body.appendChild(passwordContainer);
    
    // 添加密码验证样式
    const style = document.createElement('style');
    style.textContent = `
      #passwordContainer {
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        display: flex;
        align-items: center;
        justify-content: center;
        z-index: 9999;
      }
      
      .password-dialog {
        background: rgba(255, 255, 255, 0.95);
        backdrop-filter: blur(10px);
        border-radius: 20px;
        padding: 40px;
        text-align: center;
        box-shadow: 0 20px 40px rgba(0, 0, 0, 0.3);
        min-width: 300px;
        animation: passwordFadeIn 0.5s ease-out;
      }
      
      @keyframes passwordFadeIn {
        from {
          opacity: 0;
          transform: translateY(-30px) scale(0.9);
        }
        to {
          opacity: 1;
          transform: translateY(0) scale(1);
        }
      }
      
      .password-header h2 {
        margin: 0 0 10px 0;
        color: #333;
        font-size: 24px;
      }
      
      .password-header p {
        margin: 0 0 30px 0;
        color: #666;
        font-size: 14px;
      }
      
      .password-form {
        margin-bottom: 20px;
      }
      
      #passwordInput {
        width: 100%;
        padding: 12px 16px;
        border: 2px solid #e1e5e9;
        border-radius: 10px;
        font-size: 16px;
        margin-bottom: 15px;
        box-sizing: border-box;
        transition: border-color 0.3s ease;
      }
      
      #passwordInput:focus {
        outline: none;
        border-color: #667eea;
        box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
      }
      
      #verifyBtn {
        width: 100%;
        padding: 12px;
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        border: none;
        border-radius: 10px;
        font-size: 16px;
        cursor: pointer;
        transition: transform 0.2s ease;
      }
      
      #verifyBtn:hover {
        transform: translateY(-2px);
      }
      
      .password-footer p {
        margin: 0;
        color: #888;
        font-size: 12px;
      }
      
      .password-footer strong {
        color: #667eea;
      }
      
      .error-message {
        color: #e74c3c;
        font-size: 14px;
        margin-top: 10px;
        animation: shake 0.5s ease-in-out;
      }
      
      @keyframes shake {
        0%, 20%, 40%, 60%, 80% {
          transform: translateX(-5px);
        }
        10%, 30%, 50%, 70%, 90% {
          transform: translateX(5px);
        }
      }
    `;
    document.head.appendChild(style);
    
    // 绑定验证事件
    const passwordInput = document.getElementById('passwordInput');
    const verifyBtn = document.getElementById('verifyBtn');
    
    // 回车键验证
    passwordInput.addEventListener('keypress', function(e) {
      if (e.key === 'Enter') {
        verifyPassword();
      }
    });
    
    // 按钮点击验证
    verifyBtn.addEventListener('click', verifyPassword);
    
    // 自动聚焦
    passwordInput.focus();
  }
  
  // 验证密码
  function verifyPassword() {
    const passwordInput = document.getElementById('passwordInput');
    const verifyBtn = document.getElementById('verifyBtn');
    const password = passwordInput.value.trim();
    
    // 设置正确的密码（您可以修改这个密码）
    const correctPassword = 'nmbff188';
    
    if (password === correctPassword) {
      // 密码正确，保存验证状态
      chrome.storage.local.set({ passwordVerified: true }, function() {
        // 显示成功提示
        showSuccessMessage();
        
        // 延迟后初始化插件
        setTimeout(() => {
          document.getElementById('passwordContainer').remove();
          document.querySelector('.container').style.display = 'flex';
          initializeExtension();
        }, 1500);
      });
    } else {
      // 密码错误
      showErrorMessage('密码错误，请重新输入');
      passwordInput.value = '';
      passwordInput.focus();
    }
  }
  
  // 显示成功消息
  function showSuccessMessage() {
    const dialog = document.querySelector('.password-dialog');
    dialog.innerHTML = `
      <div class="password-header">
        <h2 style="color: #27ae60;">✅ 验证成功</h2>
        <p>正在启动插件...</p>
      </div>
    `;
  }
  
  // 显示错误消息
  function showErrorMessage(message) {
    // 移除之前的错误消息
    const existingError = document.querySelector('.error-message');
    if (existingError) {
      existingError.remove();
    }
    
    // 添加新的错误消息
    const errorDiv = document.createElement('div');
    errorDiv.className = 'error-message';
    errorDiv.textContent = message;
    document.querySelector('.password-form').appendChild(errorDiv);
  }
  
}); 